#!/usr/bin/python
import os, re, sys

strutfdict = {}
structMemType = ['PTR_ENCODE', 'WORD32', ]
lineNum = 0

def error(linenum, line):
    print 'error occured in line: %d' % linenum
    print lin
    if line == '':
        return None
    line = line.rstrip()
    line = re.sub('\/\*.*\*\/', '', line)  #remove comments
    funcMatch = re.match(funcDefpatten, line) 
    if funcMatch and not isKeyWordLine(line):
        #print line
        #print funcMatch.groups()           #get func para
        #print funcMatch.group(2).split()[1]
        paraTpye = funcMatch.group(2).split()[1]
        paraList.append(paraTpye)
        #print paraList
        #getStructdef('tags', paraTpye)
        return line
    else:
        return ''

def getFuncBody(file):
    funBody = []
    line = getNextLine(file)
    while None == re.match('\s*{\s*', line):
        line = getNextLine(file)
    line = getNextLine(file)
    while None == re.match('}\s*', line):
        funBody.append(line)
        line = getNextLine(file)
    return

def checkFuncLine(line, structList):
    funcCallPatten = '.*ENCODE.*->([a-zA-Z0-9]*).*->(.*)\).*'
    funcCallMatch = re.match(funcCallPatten, line) 
    if funcCallMatch:
        if funcCallMatch.group(1) != funcCallMatch.group(2):
            error(lineNum, line)
        structList.append(funcCallMatch.group(1))

def checkFuncBody(file, paraType):
    funBody = []
    structList = []
    startLineNum = lineNum
    line = getNextLine(file)
    while None == re.match('\s*{\s*', line):
        line = getNextLine(file)
    line = getNextLine(file)
    while None == re.match('}\s*', line):
        funBody.append(line)
        checkFuncLine(line, structList)
        line = getNextLine(file)
    structList.sort()
    if structList != strutfdict[paraType]:
        print 'error occured betwwen line %d and line %d ' % (startLineNum,
        lineNum)
    #print structList
    return

def checkFile(file):
    paraList = []
    line = getEncodeFuncdef(cfile, paraList)
    while line != None:
        if line != '':
            getStructdef('tags', paraList[0])
            checkFuncBody(cfile, paraList[0])
            paraList = []
        line = getEncodeFuncdef(cfile, paraList)

if __name__=="__main__":
    print sys.argv[1]

    if len(sys.argv) <= 1:
        print 'Usage: ./codechk.py <file>'
    else:
        print 'check', sys.argv[1],'...'
        cfile = open(sys.argv[1])
        checkFile(cfile)
